﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace SharePoint.Contrib.Extensions
{
    /// <summary>
    /// Extension methods for the SPContentType class
    /// </summary>
    public static class SPContentTypeExtensions
    {
        /// <summary>
        /// Adds a fieldref to a content type.
        /// </summary>
        /// <param name="name">The internal name of the field</param>
        public static void AddFieldRef(this SPContentType instance, string name)
        {
            if (instance.Fields.Contains(name) == false &&
                instance.ParentWeb.Fields.Contains(name))
            {
                var field = instance.ParentWeb.Fields.GetFieldByInternalName(name);
                instance.FieldLinks.Add(new SPFieldLink(field));
                instance.Update(); 
            }

        }

        /// <summary>
        /// Adds a fieldref to a content type.
        /// </summary>
        /// <param name="id">The id of the field</param>
        public static void AddFieldRef(this SPContentType instance, Guid id)
        {
            if (instance.Fields.Contains(id) == false &&
                instance.ParentWeb.Fields.Contains(id))
            {
                var field = instance.ParentWeb.Fields[id];
                instance.FieldLinks.Add(new SPFieldLink(field));
                instance.Update();
            }

        }
    }
}
